<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;
use app\model\Customer;
use app\model\Principal;

class SemPlan extends Common
{

	/**
	 * 请求类型
	 *
	 * @return
	 */
	public function read(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semplan:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$search = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		if( in_array($sort, ['impression', 'clicks', 'cost', 'cash', 'rebate', 'copynumber', 'cpc', 'ctr', 'copycost']) ) {
			$sort = 's.'.$sort;
		} else {
			$sort = 'c.'.$sort;
		}

		array_push( $search, " s.companyId = {$request->sessInfo['companyId']} ");
		array_push( $where, ['c.companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['c.userType', '=', 1 ] );

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['c.bazaarId', '=',  $bazaarId ] );
		}

		$userId = $request->param('userId', '', 'trim');
		if($userId) {
			array_push( $where, ['c.userId', '=',  $userId ] );
		}
		
		$customerid = $request->param('customerid', '', 'trim');
		if($customerid) {
			array_push( $where, ['c.customerid', '=',  $customerid ] );
		}

		$contact = $request->param('contact', '', 'trim');
		if($contact) {
			array_push( $where, ['c.contact', '=',  $contact ] );
		}
		
		$status = $request->param('status', '', 'trim');
		if($status) {
			array_push( $where, ['c.status', '=',  $status ] );
		}

		$campaignName = $request->param('campaignName', '', 'trim');
		if($campaignName) {
			array_push( $where, ['c.campaignName', 'like', "%$campaignName%" ] );
		}
	
		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			$time = cloud_datetime_format( $createTimeStart, $createTimeEnd, true);
		} else {
			$time = cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), true);
		}

	  array_push( $search, " `s`.`datatime` BETWEEN {$time[0]} AND {$time[1]} ");
    	$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('semauthaccount');
			if($authaccount) {
				array_push( $where, ['c.userId', 'in',  $authaccount ] );
			}
		}
		$query = Db::table('cfg_campaign')
		->alias('c')
		->field('c.id, c.bazaarId, c.status, c.userId, c.customerid, c.contact, c.budget, c.campaignId, c.campaignName, c.schedule, c.exactNegativeWords, c.negativeWords, c.regionName, c.regionTarget, c.datatime,
		  sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
		->leftJoin('cfg_search s','c.campaignId = s.campaignid AND ' . implode(' AND ', $search))
		->where($where)
		->group('c.campaignid')
		->order($sort, $order)
		->paginate($limit);

    // echo  Db::getLastSql() . "\n";

    $count = $query->total();
		$items = $query->items();
		foreach($items as &$value ) {
			$value['impression'] = $value['impression'] ? $value['impression'] : 0;
			$value['clicks'] = $value['clicks'] ? $value['clicks'] : 0;
			$value['cost'] = $value['cost'] ? $value['cost'] : 0;
			$value['cash'] = $value['cash'] ? $value['cash'] : 0;
			$value['rebate'] = $value['rebate'] ? $value['rebate'] : 0;
			$value['cpc'] = $value['cpc'] ? $value['cpc'] : 0;
			$value['ctr'] = $value['ctr'] ? $value['ctr'] : 0;
			$value['copynumber'] = $value['copynumber'] ? $value['copynumber'] : 0;
			$value['copycost'] = $value['copycost'] ? $value['copycost'] : 0;
			$value['userLevel'] = Db::table('cfg_expand')->where('userid', $value['userId'])->value('userLevel');
			$exactNegativeWords = $value['exactNegativeWords'] ? unserialize($value['exactNegativeWords']) : [];
			$negativeWords = $value['negativeWords'] ? unserialize($value['negativeWords']) : [];
			$schedule = $value['schedule'] ? unserialize($value['schedule']) : [];
			$value['exactNegativeWords'] = $exactNegativeWords;
			$value['negativeWords'] = $negativeWords;
			$value['schedule'] = $schedule;
		}

		$total = Db::table('cfg_campaign')
		->alias('c')
		->field('sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
		->leftJoin('cfg_search s','c.campaignId = s.campaignid AND ' . implode(' AND ', $search))
		->where($where)
		->find();

		$total['impression'] = $total['impression'] ? $total['impression'] : 0;
		$total['clicks'] = $total['clicks'] ? $total['clicks'] : 0;
		$total['cost'] = $total['cost'] ? $total['cost'] : 0;
		$total['cash'] = $total['cash'] ? $total['cash'] : 0;
		$total['rebate'] = $total['rebate'] ? $total['rebate'] : 0;
		$total['cpc'] = $total['cpc'] ? $total['cpc'] : 0;
		$total['ctr'] = $total['ctr'] ? $total['ctr'] : 0;
		$total['copynumber'] = $total['copynumber'] ? $total['copynumber'] : 0;
		$total['copycost'] = $total['copycost'] ? $total['copycost'] : 0;

		return ['code'=> 0, 'msg'=> '', 'count'=> $count, 'data'=> $items, 'total' => $total,
			'expand' => Expand::getList($request->sessInfo, 1),
		  'customer' => Customer::getList($request->sessInfo),
		  'principal' => Principal::getList($request->sessInfo),
			'bazaar' => Bazaar::getList($request->sessInfo, 1)];
	}

	/**
	* 同步百度官方计划
	*
	* @param tValue
	* @return
	*/
	public function getCloud(Request $request) {
		if($this->hasPermission($request->sessInfo, 'semplan:cloud')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$userId = $request->param('userId', '', 'trim');
		if( empty($userId) ) {
			return ['code'=> 403, 'msg'=> '请选择要同步的账号!'];
		}
		
		$obj = Expand::getUserInfo($request->sessInfo, $userId, 1);
		if(!is_object($obj)) {
			return ['code'=> 403, 'msg'=> '数据异常,请稍后重试!'];
		}

		$response = doPostRequest('https://api.baidu.com/json/sms/service/CampaignService/getCampaign', json_encode([
			'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
			'body'=> [
        "campaignFields"=> [
            "campaignId",
            "campaignName",
            "budget",
            "negativeWords",
            "exactNegativeWords",
            "status",
        ],
        "mobileExtend"=> 1,
        "adType"=> 0
			]
		]));

		if(empty($response)) {
			return json(['code'=> 403, 'msg'=> 'network anomaly detection.!']);
		}

		$result = json_decode ($response, true);
		if(!isset($result['header']['desc'])){
			return json(['code'=> 403, 'msg'=> 'network anomaly detection.!']);
		}

		if(!isset($result['header']['desc'])) {
			return json(['code'=> 403, 'msg'=> 'network anomaly detection.!']);
		}

		if($result['header']['desc'] == 'failure') {
			$tempMessage  = explode('sn:', $result['header']['failures'][0]['message']);
			return json(['code'=> 403, 'msg'=> 'code: ' . $result['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] ]);
		}

    $campaignIdArray = [];
    if(is_array($result['body']['data'])) {
			foreach($result['body']['data'] as $value) {
				array_push($campaignIdArray, $value['campaignId']);
				$value['budget'] = isset($value['budget']) ? $value['budget'] : 0;
				$campaignId = Db::table('cfg_campaign')->where('companyId', $request->sessInfo['companyId'])->where('campaignId', $value['campaignId'])->value('id');
				if($campaignId) {
					Db::name('cfg_campaign')->where('campaignId', $value['campaignId'])->update([
						'campaignName' =>  $value['campaignName'],
						'budget' => $value['budget'],
						'contact' => $obj->contact,
						'customerid' => $obj->customerid,
						'datatime' => date('Y-m-d H:i:s'),
						'negativeWords' => serialize($value['negativeWords']),
						'exactNegativeWords' => serialize($value['exactNegativeWords']),
						'status' => $value['status'],
					]);
				} else {
					Db::name('cfg_campaign')->insert([
					  'companyId' => $request->sessInfo['companyId'],
						'userType' => 1,
						'userId' => $obj->userid,
						'contact' => $obj->contact,
						'customerid' => $obj->customerid,
						'bazaarId' => $obj->bazaarId,
						'budget' => $value['budget'],
						'datatime' => date('Y-m-d H:i:s'),
						'campaignId' =>  $value['campaignId'],
						'campaignName' =>  $value['campaignName'],
						'negativeWords' => serialize($value['negativeWords']),
						'exactNegativeWords' => serialize($value['exactNegativeWords']),
						'status' => $value['status']
					]);
				}
			}

			if(count($campaignIdArray) > 0){
				Db::table('cfg_campaign')->where('companyId', $request->sessInfo['companyId'])->where('userId', $obj->userid)
				  ->where('userType', 1)->whereNotIn('campaignId', $campaignIdArray)->delete();
			}

		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>[]]);
	}

	/**
	* 计划执行地址
	*
	* @param tValue
	* @return
	*/
	private function updateCampaign($parameter) {
		$request = doPostRequest('https://api.baidu.com/json/sms/service/CampaignService/updateCampaign', $parameter);
		if(empty($request)) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		$result = json_decode ($request, true);
		if(!isset($result['header']['desc'])){
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		if(!isset($result['header']['desc'])) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		return $result;
	}

	/**
	 * 设置计划每日预算
	 *
	 * @return
	 */
	public function setBudget(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semplan:budget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];

		$ids = $request->param('selectId/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}

		if(count($handleId) === 0){
			return ['code'=>403, 'msg'=>'请选择要设置的计划!'];
		}

		$budgetType = $request->param('budgetType/d', '', 'trim');
		$budget = $request->param('budget/d', '', 'trim');
		if( $budgetType === 0 ) {
			$budget = 0;
		}
		$result = [];
		$beginTime = microtime(true);
		$query = Db::table('cfg_campaign')->field('id, userId, campaignId, campaignName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('campaignId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 1);
				if(is_object($obj)) {
					$response = $this->updateCampaign(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'campaignTypes'=>[
								[
									"campaignId"=> $value['campaignId'],
									"budget"=> $budget,
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						Db::name('cfg_campaign')->where('campaignId', $value['campaignId'])->update(['budget' => $budget]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '搜索计划报告', '设置计划每日预算, ' . $budget . '元', 0, null);
						array_push($result, '['.$value['campaignName'].'] 操作成功.');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '['.$value['campaignName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] );
					}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}

	/**
	 * 设置计划状态
	 *
	 * @return
	 */
	public function setPause(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semplan:userStat')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$selectId = $request->param('selectId/a', '', 'trim');
		if( count($selectId) == 0 ) {
			return ['code'=> 403, 'msg'=> '请选择要设置的计划!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$pause = $request->param('pause/d', '', 'trim');
		$query = Db::table('cfg_campaign')->field('id, userId, campaignId, campaignName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $selectId)->group('campaignId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 1);
				if(is_object($obj)) {
					$response = $this->updateCampaign(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'campaignTypes'=>[
								[
									"campaignId"=> $value['campaignId'],
									"pause"=> $pause,
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						$status = 21;
						if( $response['body']['data'][0]['pause'] ) {
							$status = 23;
						}
						Db::name('cfg_campaign')->where('campaignId', $value['campaignId'])->update(['status' => $status]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '搜索计划报告', '设置计划状态, ' . $pause, 0, null);
						array_push($result, '['.$value['campaignName'].'] 操作成功.');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '['.$value['campaignName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] );
					}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}

	/**
	 * 设置计划推广时段
	 *
	 * @return
	 */
	public function setHour(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semplan:schedule')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];

		$ids = $request->param('selectId/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}

		if(count($handleId) === 0) {
			return ['code'=>403, 'msg'=>'请选择要设置的计划!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$scheduleName = '自定义时段';
		$hourType = $request->param('hourType', '', 'trim');
		$schedule = $request->param('schedule/a', '', 'trim');
		if($hourType == 0 || count($schedule) == 168) {
			$schedule = [];
			$scheduleName = '全部时段';
		}

    $_schedule = [];
		for ($i=1; $i<=7; $i++) {
			$startHour = [];
			foreach($schedule as $key => $value) {
				if($value['weekDay'] == $i) {
					array_push($startHour, $value['startHour']);
				}
			}
			$algorithm = getAlgorithm($startHour, $i);
			if (is_array($algorithm)) {
				foreach($algorithm as $value) {
					array_push($_schedule, $value);
				}
			}
		}

		array_multisort (array_column($_schedule, 'weekDay'), SORT_ASC, $_schedule);

		$query = Db::table('cfg_campaign')->field('id, userId, campaignId, campaignName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('campaignId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 1);
				if(is_object($obj)) {
					$response = $this->updateCampaign(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'campaignTypes'=>[
								[
									"campaignId"=> $value['campaignId'],
									"schedule"=>  $_schedule
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						Db::name('cfg_campaign')->where('campaignId', $value['campaignId'])->update(['schedule' => serialize($schedule)]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '搜索计划报告', '设置计划推广时段, ' . $scheduleName, 0, null);
						array_push($result, '<i class="el-message__icon el-icon-success"></i><span style="vertical-align:top;">['.$value['campaignName'].'] 操作成功.</span>');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '<i class="el-message__icon el-icon-error"></i><span style="vertical-align:top;">['.$value['campaignName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] . '</span>');
					}
				}
			}
		}
    return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=> $result]);
	}

	/**
	 * 设置计划推广否定词
	 *
	 * @return
	 */
	public function setWords(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semplan:words')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];

		$ids = $request->param('selectId/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}

		if(count($handleId) === 0){
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}

		$exactNegativeWordsArray = [];
		$exactNegativeWords = $request->param('exactNegativeWords', '', 'trim');
		$tempexactNegativeWordsArray = explode("\n", $exactNegativeWords);
		foreach( $tempexactNegativeWordsArray as $value  ) {
			$value = trim($value);
			if($value && !in_array($value, $exactNegativeWordsArray)) {
				array_push($exactNegativeWordsArray, $value);
			}
		}

    $negativeWordsArray = [];
		$negativeWords = $request->param('negativeWords', '', 'trim');
		$tempnegativeWordsArray = explode("\n", $negativeWords);
		foreach( $tempnegativeWordsArray as $value  ) {
			$value = trim($value);
			if($value && !in_array($value, $negativeWordsArray)) {
				array_push($negativeWordsArray, $value);
			}
		}

		$result = [];
		$beginTime = microtime(true);
		$query = Db::table('cfg_campaign')->field('id, userId, campaignId, campaignName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('campaignId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 1);
				if(is_object($obj)) {
					$response = $this->updateCampaign(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'campaignTypes'=>[
								[
									"campaignId"=> $value['campaignId'],
									"negativeWords"=> $negativeWordsArray,
									"exactNegativeWords"=> $exactNegativeWordsArray,
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						$negativeWords = isset($response['body']['data'][0]['negativeWords']) ? $response['body']['data'][0]['negativeWords'] : [];
						$exactNegativeWords = isset($response['body']['data'][0]['exactNegativeWords']) ? $response['body']['data'][0]['exactNegativeWords'] : [];
						Db::name('cfg_campaign')->where('campaignId', $value['campaignId'])->update(['exactNegativeWords' => serialize($exactNegativeWords), 'negativeWords' => serialize($negativeWords)]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '搜索计划报告', '设置计划推广否定关键词, ', 0, null);
						array_push($result, '<i class="el-message__icon el-icon-success"></i><span style="vertical-align:top;">['.$value['campaignName'].'] 操作成功.</span>');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '<i class="el-message__icon el-icon-error"></i><span style="vertical-align:top;">['.$value['campaignName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] . '</span>');
					}
				}
			}
		}
    return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=> $result]);
	}

	/**
	 * 批量设置计划推广地域
	 *
	 * @return
	 */
	public function updateRegionTarget(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semplan:regionTarget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];

		$ids = $request->param('ids/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}

		if(count($handleId) === 0){
			return ['code'=>403, 'msg'=>'请选择要设置的计划!'];
		}

		$regionName = '';
		$regionTarget = [];
		$regionPriceFactor = [];
		$regionTargetData = $request->param('regionTarget', '', 'trim');
		$regionTargetArray = json_decode($regionTargetData);
		if(count($regionTargetArray ) > 0){
			$cityNumber = 0;
			foreach( $regionTargetArray as $value) {
				if(in_array($value->id, [ 1000, 2000, 3000, 33000, 34000, 35000, 36000])) {
					$cityNumber++;
			    $regionName = $value->label;
					array_push($regionTarget, $value->id);
					array_push($regionPriceFactor, ['regionId'=> $value->id, 'priceFactor'=>$value->priceFactor]);
				}
				foreach( $value->children as $key => $item) {
					if($key == 0 ) {
						$regionName = $item->label;
					}
					$cityNumber++;
					array_push($regionTarget, $item->id);
					array_push($regionPriceFactor, ['regionId'=> $item->id, 'priceFactor'=>$item->priceFactor]);
				}
			}
			$regionName = $regionName . '等' . $cityNumber . '个';
		}

		if( count($regionTarget) == 0 ) {
			return ['code'=>403, 'msg'=>'请至少选择一个地域!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$query = Db::table('cfg_campaign')->field('id, userId, campaignId, campaignName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('campaignId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 1);
				if(is_object($obj)) {
					$response = $this->updateCampaign(json_encode([
						'header'=> ['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'campaignTypes'=>[
								[
									"campaignId"=> $value['campaignId'],
									'regionTarget' => $regionTarget,
									'regionPriceFactor'=> $regionPriceFactor,
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						Db::name('cfg_campaign')->where('campaignId', $value['campaignId'])->update(['regionName' => $regionName, 'regionTarget' => $regionTargetData]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '搜索计划报告', '设置计划推广地域' . $regionName , 0, null);
							array_push($result, '<i class="el-message__icon el-icon-success"></i><span style="vertical-align:top;">['.$value['campaignName'].'] 操作成功.</span>');
						} else {
							$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
							array_push($result, '<i class="el-message__icon el-icon-error"></i><span style="vertical-align:top;">['.$value['campaignName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] . '</span>');
						}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}

	/**
	 * 查询推广地域
	 *
	 * @return
	 */
	public function regionTarget(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semplan:regionTarget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'请选择要查询的计划!'];
		}
		$query = Db::table('cfg_campaign')->field('id, regionTarget')->where('id', $id)->where('companyId', $request->sessInfo['companyId'])->find();
		if(!isset($query['id'])) {
			return ['code'=>403, 'msg'=>'非法请求id不存在!'];
		}
		$query['regionTarget'] = json_decode($query['regionTarget']);
		return json(['code'=>0, 'data' => $query, 'msg'=>'']);
	}

}
